package com.yidu.qianfeng.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * @Author: TangSheng
 * @Description: redis视图控制层+业务
 * @Date Created in 19:10 2021/4/23
 * @since 1.0
 */

@Controller
public class RedisController {


    @Autowired
    private RedisTemplate<String,Map<String,String>> template;


    @RequestMapping("/waybillVolume")
    @ResponseBody
    public String waybillVolume(String nowMonth){
        List<Object> year2021 = template.opsForHash().values("year2021");
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = "";
        try {
            jsonStr = objectMapper.writeValueAsString(year2021);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return jsonStr;
    }

    @RequestMapping("/waybillVolumeUpdate")
    @ResponseBody
    public String waybillVolumeUpdate(String nowMonth){

        Integer volume = (Integer)template.opsForHash().get("year2021", nowMonth);
        int ran=(int)(Math.random()*30);
        template.opsForHash().put("year2021", nowMonth,volume+ran);
        List<Object> year2021 = template.opsForHash().values("year2021");
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = "";
        try {
            jsonStr = objectMapper.writeValueAsString(year2021);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return jsonStr;
    }

}
